package com.jiexin.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jiexin.exception.ParamException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * @Author: Jay_Liu
 * @Description: 校验包含报错信息的返回
 * @Date: Created in 20:46 2018/4/1 0001
 * @Modified By:
 */
public class BeanValidator {

    //全局校验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> Map<String,String> validate(T t, Class... groups){
        Validator validator = validatorFactory.getValidator();
        //自动获取校验结果
        Set validateResult = validator.validate(t, groups);
        //
        if (validateResult.isEmpty()) {
            //若为空返回一个空的map
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator =validateResult.iterator();
            while (iterator.hasNext()){
                //每一行都是一个校验的结果类
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                //校验的结果(Key-Value:有问题字段-问题信息)
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    public static Map<String, String> validateList(Collection<?> collection){
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if(!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while(errors.isEmpty());

        return errors;
    }

    public static Map<String, String> validateObject(Object first, Object... objects){
        if (objects != null && objects.length > 0){
            return validateList(Lists.asList(first,objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    /**
     * 使用自定义的类进行处理
     * @param param
     * @throws ParamException
     */
    public static void check(Object param) throws ParamException {

        Map<String, String> map = BeanValidator.validateObject(param);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }

    public static void main(String[] args) {
    }

}
